package vn.com.vega.chacha.v2;

import java.lang.ref.WeakReference;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.Asynctask.AutoLogin;
import vn.com.vega.chacha.v2.Asynctask.AutoLogin.LoginListener;
import vn.com.vega.chacha.v2.receiver.NetworkStatusReceiver;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.utils.VegaLog;
import vn.com.vega.music.view.custom.ChaChaDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class SplashScreen extends ActivityBase {
	private static final String TAG = "SplashScreen";
	private static final int SPLASH_TIME = 1500;

	private static final int ASK_OFFLINE = 13;
	private static final int SHOW_FIRST_PROGRESS = 16;
	private static final int SHOW_SECOND_PROGRESS = 17;
	private static final int SHOW_THIRD_PROGRESS = 18;
	private static final int SHOW_FOURTH_PROGRESS = 19;
	private static final int GOTO_LOGIN = 22;
	private static final int GOTO_MAIN = 23;

	private DataStore dataStore;
	private ProgressBar mProgressBar;
	private AutoLogin autoLogin;
	private Toast mToast;
	private boolean pause;
	private MediaPlayer mPlayer;
	private boolean isPlaySoundFinish = false;

	private void gotoOfflineMode(String msg) {
		final ChaChaDialog offRequest = new ChaChaDialog(this, null);
		offRequest.setTitle(this.getString(R.string.dilog_title_default));
		offRequest.setMessage(msg);
		View.OnClickListener yesClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent off = new Intent(SplashScreen.this, LocalSongScreen.class);
				startActivity(off);
				finish();
				offRequest.dismiss();
			}
		};

		View.OnClickListener noClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				offRequest.dismiss();
			}
		};

		offRequest.addButton(this.getString(R.string.confirm_yes),
				yesClickListener);
		offRequest.addButton(this.getString(R.string.confirm_no),
				noClickListener);
		offRequest.hideCloseDefaultBtn();
		offRequest.show();
	}

	static class WelcomeHandler extends Handler {
		WeakReference<SplashScreen> welcomeAct;

		public WelcomeHandler(SplashScreen act) {
			welcomeAct = new WeakReference<SplashScreen>(act);
		}

		@Override
		public void handleMessage(Message msg) {
			SplashScreen welcome = welcomeAct.get();
			if (welcome == null || welcome.isDestroy) {
				return;
			}
			switch (msg.what) {
			case GOTO_LOGIN:
				if (welcome.isPlaySoundFinish) {
					welcome.gotoLogin();
				} else {
					sendEmptyMessageDelayed(GOTO_LOGIN, 100);
				}
				break;
			case GOTO_MAIN:
				if (welcome.isPlaySoundFinish) {
					welcome.gotoMainScreen();
				} else {
					sendEmptyMessageDelayed(GOTO_MAIN, 100);
				}
				break;
			// case ASK_OFFLINE:
			// welcome.gotoOfflineMode(welcome
			// .getString(R.string.setting_question_switch_to_offline));
			// break;
			case SHOW_FIRST_PROGRESS:
				if (welcome.mProgressBar != null)
					welcome.mProgressBar.setProgress(25);
				break;
			case SHOW_SECOND_PROGRESS:
				if (welcome.mProgressBar != null)
					welcome.mProgressBar.setProgress(50);
				break;
			case SHOW_THIRD_PROGRESS:
				if (welcome.mProgressBar != null)
					welcome.mProgressBar.setProgress(75);
				break;
			case SHOW_FOURTH_PROGRESS:
				if (welcome.mProgressBar != null)
					welcome.mProgressBar.setProgress(100);
				break;
			}
		}
	}

	WelcomeHandler mHandler = new WelcomeHandler(SplashScreen.this);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		VegaLog.e(TAG, "On create");

		setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
		setContentView(R.layout.layout_activity_splash);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		// mApp = (ChaChaAppInstant) getApplication();

		mProgressBar = (ProgressBar) findViewById(R.id.splash_progress_bar);

		dataStore = DataStore.getInstance();
		if (dataStore.isInOfflineMode()) {
			// TODO: go to off mode
		}

		if (!NetworkStatusReceiver.isConnected()) {
			gotoOfflineMode(getString(R.string.setting_question_switch_to_offline));
			return;
		}
		mHandler.sendEmptyMessage(SHOW_FIRST_PROGRESS);

		// check if user is Logout
		String isLogout = dataStore.getConfig(Const.KEY_IS_LOGOUT);
		if (isLogout != null && isLogout.equalsIgnoreCase("true")) {
			mHandler.sendEmptyMessageDelayed(SHOW_FOURTH_PROGRESS,
					SPLASH_TIME - 500);
			mHandler.sendEmptyMessageDelayed(GOTO_LOGIN, SPLASH_TIME);
			return;
		}

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(NetworkStatusReceiver.NETWORK_CHANGE);
		intentFilter.addAction(NetworkStatusReceiver.NETWORK_OFF);
		LocalBroadcastManager.getInstance(this).registerReceiver(
				netWorkListener, intentFilter);

		if (autoLogin != null) {
			autoLogin.cancel(true);
		}
		autoLogin = new AutoLogin(this, loginListener);
		autoLogin.execute();
		playSoundWelComeChaCha();
	}

	private BroadcastReceiver netWorkListener = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(NetworkStatusReceiver.NETWORK_OFF)) {
				// TODO: stop auto login, ask offline mode
				if (autoLogin != null) {
					autoLogin.cancel(true);
				}
				gotoOfflineMode(getString(R.string.setting_question_switch_to_offline));
			} else if (action.equals(NetworkStatusReceiver.NETWORK_CHANGE)) {
				// TODO: retry auto login
				if (autoLogin != null) {
					autoLogin.cancel(true);
				}
				autoLogin = new AutoLogin(SplashScreen.this, loginListener);
				autoLogin.execute();
			}
		}
	};

	private LoginListener loginListener = new LoginListener() {

		@Override
		public void startLogin() {
			// TODO Auto-generated method stub
			mHandler.sendEmptyMessage(SHOW_SECOND_PROGRESS);
		}

		@Override
		public void loginSuccess() {
			// TODO Auto-generated method stub
			mHandler.sendEmptyMessage(SHOW_FOURTH_PROGRESS);
			// TODO: go in app.
			mHandler.sendEmptyMessage(GOTO_MAIN);
		}

		@Override
		public void loginFail(String failMessage) {
			// TODO Auto-generated method stub
			if (!Util.checkStringIsemptyOrNull(failMessage)) {
				mToast.setText(failMessage);
				mToast.show();
			}
			mHandler.sendEmptyMessage(SHOW_FOURTH_PROGRESS);
			mHandler.sendEmptyMessage(GOTO_LOGIN);
		}
	};

	private void gotoLogin() {
		if (pause) {
			mHandler.removeMessages(GOTO_LOGIN);
			mHandler.sendEmptyMessageDelayed(GOTO_LOGIN, 300);
			return;
		}
		Intent login = new Intent(this, LoginActivity.class)
				.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(login);
		finish();
	}

	private void gotoMainScreen() {
		if (pause) {
			mHandler.removeMessages(GOTO_MAIN);
			mHandler.sendEmptyMessageDelayed(GOTO_MAIN, 300);
			return;
		}
		Intent inten = new Intent(SplashScreen.this, MainScreen.class);
		startActivity(inten);
		finish();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		VegaLog.e(TAG, "onDestroy");
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				netWorkListener);
		mHandler.removeCallbacksAndMessages(null);
		if (autoLogin != null) {
			autoLogin.cancel(true);
		}
		try {
			if (mPlayer != null) {
				mPlayer.release();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// mHandler.removeCallbacksAndMessages(null);
		// mHandler = new WelcomeHandler(null);
		pause = true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		pause = false;
	}

	@Override
	protected void logoutListener() {
		// TODO Auto-generated method stub
		// Do nothing here
	}

	@Override
	protected void unListenerLogout() {
		// TODO Auto-generated method stub
		// Do nothing here
	}

	private void playSoundWelComeChaCha() {
		new Thread() {
			@Override
			public void run() {
				try {
					mPlayer = new MediaPlayer();
					AssetFileDescriptor afd = getAssets().openFd(
							"ChaChaStartUp.mp3");
					mPlayer.setDataSource(afd.getFileDescriptor(),
							afd.getStartOffset(), afd.getLength());
					mPlayer.setOnPreparedListener(onPreparedListener);
					mPlayer.setOnErrorListener(onErrorListener);
					mPlayer.setOnCompletionListener(completionListener);
					mPlayer.setAudioStreamType(AudioManager.STREAM_RING);
					mPlayer.setVolume(1.0f, 1.0f);
					mPlayer.prepareAsync();
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		}.start();
	}

	private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {

		@Override
		public boolean onError(MediaPlayer mp, int what, int extra) {
			// TODO Auto-generated method stub
			isPlaySoundFinish = true;
			return false;
		}
	};

	private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
		@Override
		public void onPrepared(MediaPlayer mp) {
			// TODO Auto-generated method stub
			mPlayer.start();
		}
	};

	private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {

		@Override
		public void onCompletion(MediaPlayer mp) {
			// TODO Auto-generated method stub
			isPlaySoundFinish = true;
		}
	};
}
